package cn.lnexin.dingtalk.controller;

import cn.lnexin.dingtalk.constant.DingProperties;
import cn.lnexin.dingtalk.entity.User;
import cn.lnexin.dingtalk.service.IDingAuthService;
import cn.lnexin.dingtalk.service.IUserService;
import cn.lnexin.dingtalk.utils.JsonTool;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * [钉钉] - 1. 用户登陆, 用户信息获取
 *
 * @author work.lnexin@foxmail.com
 * @Description TODO
 **/
@RestController
@RequestMapping("/ding")
public class UserController {
    static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    IUserService dingUserService;

    @Autowired
    IDingAuthService dingAuthService;

    @Autowired
    DingProperties dingProperties;

    /**
     * 根据前台初始化后获取的免登授权码获取用户信息
     *
     * @param code   免登授权码
     * @param corpId 企业应用corpId
     * @return
     */
    @GetMapping("/login")
    public Map<String,Object> authCodeLogin(@RequestParam("code") String code,
                                      @RequestParam("corpId") String corpId) {
        String corpAccessToken = dingAuthService.getAccessToken(corpId);
        String userID = dingUserService.getUserId(code, corpAccessToken);
        User userItem = dingUserService.getUserItem(corpAccessToken, userID);


        Map<String, Object> result = new LinkedHashMap<>();
        result.put("code", code);
        result.put("token", corpAccessToken);
        if (userItem != null) {
            userItem.setCorpId(corpId);
        } else {
            userItem = new User();
        }

        result.put("user", userItem);

        logger.debug("[钉钉] 用户免登, 根据免登授权码code, corpId获取用户信息, code: {}, corpId:{}, result:{}", code, corpId, result);

        return result;
    }

    /**
     * 根据企业corpId获取token
     *
     * @param corpId 企业应用corpId
     * @return
     */
    @GetMapping("/token")
    public Map<String, Object> getAccessToken(@RequestParam("corpId") String corpId) {
        Map<String, Object> tokenMap = dingAuthService.getAccessTokenMap(corpId);
        logger.debug("[钉钉] 根据corpId 获取accessToken ,corpId:{}, accessToken:{}", corpId, tokenMap);
        return tokenMap;
    }

    @GetMapping("/config")
    public JsonNode getConfig() {
        return JsonTool.getNode(dingProperties.toJson());
    }

}
